// Copyright 2022 Jeroen van Nugteren

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <armadillo>

#include "rat/common/gmshfile.hh"
#include "rat/common/serializer.hh"

#include "dfpolygon.hh"
#include "distmesh2d.hh"
#include "dfscale.hh"
#include "dfcircle.hh"

// main
int main(){
	// settings
	const rat::fltp h0 = RAT_CONST(6e-3);
	
	// create mesh
	rat::dm::ShDistMesh2DPr mymesh = rat::dm::DistMesh2D::create();

	// initial edge length
	mymesh->set_h0(h0);
	mymesh->set_quad(true);

	// arma::Mat<rat::fltp> v(6,2);
	// v.row(0) = arma::Row<rat::fltp>::fixed<2>{-0.0050,0.0130};
	// v.row(1) = arma::Row<rat::fltp>::fixed<2>{-0.0050,0.0316};
	// v.row(2) = arma::Row<rat::fltp>::fixed<2>{0.1733,0.0057};
	// v.row(3) = arma::Row<rat::fltp>::fixed<2>{0.1733,0};
	// v.row(4) = arma::Row<rat::fltp>::fixed<2>{0.0683,0};
	// v.row(5) = arma::Row<rat::fltp>::fixed<2>{0.0683,0.0130};

	// wedge
	arma::Mat<rat::fltp> v(4,2);
	v.row(0) = arma::Row<rat::fltp>::fixed<2>{0,0};
	v.row(1) = arma::Row<rat::fltp>::fixed<2>{0.2,0.0};
	v.row(2) = arma::Row<rat::fltp>::fixed<2>{0.2,0.005};
	v.row(3) = arma::Row<rat::fltp>::fixed<2>{0,0.02};
	
	// the distance function
	mymesh->set_distfun(rat::dm::DFPolygon::create(arma::flipud(v)));

	// setup mesh
	mymesh->setup();
	
	// get mesh
	arma::Mat<arma::uword> q = mymesh->get_elements();
	arma::Mat<rat::fltp> p = mymesh->get_nodes();
	arma::Mat<arma::uword> es = mymesh->get_surface_edges();

	// write to gmsh
	mymesh->export_gmsh(rat::cmn::GmshFile::create("structure.gmsh"));

	// write to output file
	rat::cmn::ShSerializerPr slzr = rat::cmn::Serializer::create();
	slzr->flatten_tree(mymesh); slzr->export_json("structure.json");

	return 0;
}